package com.lhb.user.service.impl;

import com.lhb.common.threadlocal.UserContext;
import com.lhb.user.constant.Sender;
import com.lhb.user.mapper.PassengerMapper;
import com.lhb.user.mapper.UserMapper;
import com.lhb.user.model.ModifyEmailModel;
import com.lhb.user.model.ModifyPasswordModel;
import com.lhb.user.model.Passenger;
import com.lhb.user.model.User;
import com.lhb.user.service.UserInfoService;
import com.lhb.user.utils.AESEncryptor;
import com.lhb.user.utils.CodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 86131
 * @version 1.0
 * @description
 * @date 2025/8/2 下午10:56
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    PassengerMapper passengerMapper;
    @Autowired
    CodeUtil codeUtil;
    @Override
    public void modifyPassword(ModifyPasswordModel modifyPasswordModel)  {
      User user= userMapper.getUserById(modifyPasswordModel.getId());
        String oldPassword= null;
        try {
            oldPassword = AESEncryptor.decrypt(user.getPassword());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(!oldPassword.equals(modifyPasswordModel.getOldPassword())){
          throw new RuntimeException("旧密码不正确,请重新输入");
      }
        try {
            userMapper.modifyPassword(modifyPasswordModel.getId(),AESEncryptor.encrypt(modifyPasswordModel.getNewPassword()));
        } catch (Exception e) {
            throw new RuntimeException("服务器异常");
        }

    }

    @Override
    public void modifyEmail(ModifyEmailModel modifyEmailModel) throws Exception {

        if(!codeUtil.same(modifyEmailModel.getEmail(), Sender.EmailVerificationCode, modifyEmailModel.getCode()))
        {
            throw new RuntimeException("验证码过期，请重新获取验证码");
        }

        User user = userMapper.getUserById(UserContext.getUser());
        if(!modifyEmailModel.getPassword().equals(AESEncryptor.decrypt(user.getPassword())))
        {
            throw new RuntimeException("密码不正确，请重新输入");
        }

        userMapper.modifyEmail(UserContext.getUser(),AESEncryptor.encrypt(modifyEmailModel.getEmail()));


    }

    @Override
    public Passenger addPassenger(Passenger passenger) {
        if (passenger.getId()==null) {
            passenger.setUserId(UserContext.getUser());
            passengerMapper.addPassenger(passenger);
        }else{
            passengerMapper.deletePassenger(passenger.getId());
            passenger.setUserId(UserContext.getUser());
            passengerMapper.addPassenger(passenger);
        }

        return passenger;
    }

    @Override
    public List<Passenger> getPassenger() {


        return passengerMapper.getPassenger(UserContext.getUser());
    }

    @Override
    public void deletePassenger(Long id) {
        passengerMapper.deletePassenger(id);
    }
}
